﻿using System;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Diagnostics;

namespace ClientPolicy
{
    public partial class ClientUpdate : Form
    {
        public ClientUpdate()
        {
            InitializeComponent();
        }

        private void ClientUpdate_Load(object sender, EventArgs e)
        {
            timer1.Enabled = true;

        }

        private byte[] downloadedData;
        //Connects to a URL and attempts to download the file
        int bytebuffer = 1024; //set cai nay de tang toc do down.
        private void downloadData(string url)
        {
            string Link = "http://hfc.lbc.com.vn/tool/update/it/";
            url = Link + url;
            progressBar1.Visible = true;
            progressBar1.Value = 0;
            downloadedData = new byte[0];
            try
            {
                //Optional
                this.Text = "Connecting...";
                Application.DoEvents();

                //Get a data stream from the url
                WebRequest req = WebRequest.Create(url);
                WebResponse response = req.GetResponse();
                Stream stream = response.GetResponseStream();

                //Download in chuncks
                byte[] buffer = new byte[bytebuffer]; // old [1024]

                //Get Total Size
                int dataLength = (int)response.ContentLength;

                //With the total data we can set up our progress indicators
                progressBar1.Maximum = dataLength;
                lbProgress.Text = "0/" + dataLength.ToString();

                this.Text = "Downloading...";
                Application.DoEvents();
                //Download to memory
                //Note: adjust the streams here to download directly to the hard drive
                MemoryStream memStream = new MemoryStream();
                while (true)
                {
                    //Try to read the data
                    int bytesRead = stream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        //Finished downloading
                        progressBar1.Value = progressBar1.Maximum;
                        lbProgress.Text = dataLength.ToString() + "/" + dataLength.ToString();

                        Application.DoEvents();
                        break;
                    }
                    else
                    {
                        //Write the downloaded data
                        memStream.Write(buffer, 0, bytesRead);

                        //Update the progress bar
                        if (progressBar1.Value + bytesRead <= progressBar1.Maximum)
                        {
                            progressBar1.Value += bytesRead;
                            lbProgress.Text = progressBar1.Value.ToString() + "/" + dataLength.ToString();

                            progressBar1.Refresh();
                            Application.DoEvents();
                        }
                    }
                }

                //Convert the downloaded stream to a byte array
                downloadedData = memStream.ToArray();

                //Clean up
                stream.Close();
                memStream.Close();
            }
            catch (Exception)
            {
                //May not be connected to the internet
                //Or the URL might not exist
               // MessageBox.Show("Lỗi kết nối. không load được thư viện phần mềm");
               // Application.Exit();
            }

            // txtData.Text = downloadedData.Length.ToString();
            //this.Text = "Download Data through HTTP";
        }

        private void saveData(string fileName, int exit)
        {
            if (downloadedData != null && downloadedData.Length != 0)
            {
                this.Text = "Saving Data...";
                Application.DoEvents();
                if (File.Exists(fileName))
                    File.Delete(fileName);

                //Write the bytes to a file
                FileStream newFile = new FileStream(@fileName, FileMode.Create);
                newFile.Write(downloadedData, 0, downloadedData.Length);
                newFile.Close();
                this.Text = "Download Data";
                // MessageBox.Show("Saved Successfully");
                if (exit == 1)
                {                   
                    this.Close();
                    if (File.Exists(@"ClientPolicy.exe"))
                    {
                        System.Diagnostics.Process.Start(@"ClientPolicy.exe");
                    }
                }
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            foreach (Process proc in Process.GetProcessesByName("ClientPolicy"))
            {
                proc.Kill();
            }

            downloadData("ClientPolicy.exe");
            saveData("ClientPolicy.exe", 1);
        }
    }
}
